package com.frame.pageform;

import java.io.*;
import javax.servlet.http.*;

import com.frame.util.StreamUtils;


public class DownloadFile {
	static public final String ATTACHMENT = "attachment";

	private InputStream in;

	/**
	 * 文件名
	 */
	private String fileName;

	/**
	 * 文件长度
	 */
	private long length;

	/**
	 * 下载方式，默认为附件
	 */
	private String type = ATTACHMENT;

	public DownloadFile(byte[] data, String fileName)
	{
		this.in = new ByteArrayInputStream(data);
		this.fileName = fileName;
		this.length = data.length;
	}

	public DownloadFile(InputStream in, String fileName, long length)
	{
		this.in = in;
		this.fileName = fileName;
		this.length = length;
	}

	public String getFileName()
	{
		return fileName;
	}

	public InputStream getInputStream()
	{
		return in;
	}


	public String getType()
	{
		return type;
	}

	public void setType(String type)
	{
		this.type = type;
	}

	public void down(HttpServletResponse response) throws IOException
	{
		String fileName = this.fileName;
		String charset = "GBK";
		if (charset != null)
			fileName = new String(fileName.getBytes(charset), "ISO-8859-1");
		//设置http头
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", type + "; filename=" + fileName);

		StreamUtils.copyStream(in, response.getOutputStream());
	}

	public void dispense(HttpServletRequest request,
						 HttpServletResponse response) throws IOException
	{
		down(response);
	}
}
